package com.example.deptempmanageservice.controller;

import com.myprojects.common.pojo.Employee;
import com.myprojects.common.pojo.EmployeeExample;
import com.example.deptempmanageservice.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myprojects.common.dto.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping(value = "/employee-curd")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    /**
     * 该方法用于分页查询所有的实习员工信息
     */
    @RequestMapping(value = "/internship",method = RequestMethod.GET)
    @ResponseBody
    public Msg selectInternshipByPageNum(
            @RequestParam(value = "pn",defaultValue = "1") Integer pageNum){//普通
        PageInfo pageInfo = getSpecificEmployee(pageNum,"",(byte) 101);

        return getMsgByPageInfo(pageInfo);
    }

    /**
     * 该方法用于将实习员工更改为录取员工
     */
    @RequestMapping(value = "/internship",method = RequestMethod.PUT)
    @ResponseBody
    public Msg admitInternship(@RequestParam Integer id){
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus((byte) 102);
        Msg result = updateEmployee(employee);

        return result;
    }

    /**
     * 该方法用于将实习员工更改为离职员工
     */
    @RequestMapping(value = "/internship",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg dropoutInternship(@RequestParam Integer id){
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus((byte) 103);
        Msg result = updateEmployee(employee);

        return result;
    }


    /**
     * 该方法用于分页查询所有的正式员工信息
     */
    @RequestMapping(value = "/regular",method = RequestMethod.GET)
    @ResponseBody
    public Msg selectRegularByPageNum(
            @RequestParam(value = "pn",defaultValue = "1") Integer pageNum){//普通
        PageInfo pageInfo = getSpecificEmployee(pageNum,"",(byte) 102);

        return getMsgByPageInfo(pageInfo);
    }


    /**
     * 该方法用于分页查询所有的离职员工信息
     */
    @RequestMapping(value = "/departure",method = RequestMethod.GET)
    @ResponseBody
    public Msg selectDepartureByPageNum(
            @RequestParam(value = "pn",defaultValue = "1") Integer pageNum){//普通
        PageInfo pageInfo = getSpecificEmployee(pageNum,"",(byte) 103);

        return getMsgByPageInfo(pageInfo);
    }

    /**
     * 该方法用于将离职员工更改为实习员工
     */
    @RequestMapping(value = "/departure",method = RequestMethod.POST)
    @ResponseBody
    public Msg admitDeparture(@RequestParam Integer id){
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus((byte) 101);
        Msg result = updateEmployee(employee);

        return result;
    }

    /**
     * 该方法用于将离职员工更改为在职员工
     */
    @RequestMapping(value = "/departure",method = RequestMethod.PUT)
    @ResponseBody
    public Msg employDeparture(@RequestParam Integer id){
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus((byte) 102);
        Msg result = updateEmployee(employee);

        return result;
    }

    /**
     * 该方法用于将离职员工数据销毁
     */
    @RequestMapping(value = "/departure",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteDeparture(@RequestParam List<Integer> idList){
        Msg result = deleteLotsEmployee(idList);

        return result;
    }


    /**
     * 该方法用于根据页码、搜索字符串、和状态码来搜索特定的员工
     * @return 返回一个已分页的信息
     */
    public PageInfo getSpecificEmployee(Integer pageNum,String searchStr,Byte status){
        PageInfo pageInfo = null;
        try {
            //在查询之前调用，要设置查询的页数和每页的大小
            PageHelper.startPage(pageNum,10);
            //startPage后紧跟的查询就是一个分页查询
            EmployeeExample baseExample = new EmployeeExample();
            baseExample.createCriteria().andStatusEqualTo(status);
            List<Employee> roleList = employeeService.selectByExample(baseExample);
            //使用PageInfo包装查询后的结果，需要将pageInfo交给页面
            //将查询出来用户信息加入pageInfo，并连续显示5页
            pageInfo = new PageInfo(roleList,5);
        }catch (Exception e){
            e.printStackTrace();
        }

        return pageInfo;
    }

    public Msg getMsgByPageInfo(PageInfo pageInfo){
        Msg result ;//要返回的结果
        if (pageInfo != null){
            //生成返回成功的结果
            result = Msg.succeed();
            //将pageInfo加入返回的结果中
            result.addData("pageInfo",pageInfo);
            System.out.println(result.getDataMap());
        }else {
            result = Msg.failed();
            result.setMsg("服务端处理异常!");
        }

        return result;
    }


    /**
     * 该方法用于保存员工
     * 前端请求传Json对象则后端使用@RequestParam；
     * 前端请求传Json对象的字符串则后端使用@RequestBody。
     */
    @RequestMapping(value = "/employee",method = RequestMethod.GET)
    @ResponseBody
    public Msg selectEmployeeByPageNum(
            @RequestParam(value = "pn",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "search", defaultValue = "") String searchStr){
        Msg result;//要返回的结果
        try {
            //在查询之前调用，要设置查询的页数和每页的大小
            PageHelper.startPage(pageNum, 10);
            EmployeeExample example;
            //如果搜索条件为空
            if ("".equals(searchStr.trim())) {
                example = null;//则搜索条件为空，这样就能直接查询全部
            } else {//否则就装配搜索条件
                example = new EmployeeExample();
                try {//尝试转换，不行就算
                    Integer id = Integer.parseInt(searchStr);
                    example.or().andIdEqualTo(id);
                } catch (Exception e) {
                }
                example.or().andEmployee_nameLike("%" + searchStr + "%");
                example.or().andId_cardLike("%" + searchStr + "%");
//                example.or().andEmailLike("%" + searchStr + "%");
            }
            //startPage后紧跟的查询就是一个分页查询
            List<Employee> employeeList = employeeService.selectByExample(example);
            //使用PageInfo包装查询后的结果，需要将pageInfo交给页面
            //将查询出来用户信息加入pageInfo，并连续显示5页
            PageInfo pageInfo = new PageInfo(employeeList, 5);
            //生成返回成功的结果
            result = Msg.succeed();
            //将pageInfo加入返回的结果中
            result.addData("pageInfo", pageInfo);
            System.out.println(result.getDataMap());
        } catch (Exception e) {
            e.printStackTrace();
            result = Msg.failed();
            result.setMsg("服务端处理异常!");
        }

        return result;
    }

    /**
     * 该方法用于保存员工
     * 前端请求传Json对象则后端使用@RequestParam；
     * 前端请求传Json对象的字符串则后端使用@RequestBody。
     */
    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmployee(@Valid @RequestBody Employee employee,
                            BindingResult result){
        Msg msg = null;
        System.out.println("传入的employee为:"+employee+"   :");
        //先检查用户信息有没有错误
//        Map<String,Object> errorMap = employeeService.checkCreateRole(employee,result);

        //如果都无误，则尝试保存
        if (true){
            //新建该员工，并返回新建改动的数量
            int backRoleID = employeeService.insertSelective(employee);
            if (backRoleID > 0){
                msg = Msg.succeed();
                msg.setMsg("保存员工成功！");
            }else {
                msg = Msg.failed();
                msg.setMsg("保存员工失败！");
            }
        }else {
            msg = Msg.failed();
            msg.setMsg("保存员工失败！");
            //将详细错误信息添加进msg
//            msg.addData("fieldErrors",errorMap);
        }

        return msg;
    }


    /**
     * 该方法用于一次删除多个员工
     */
    @RequestMapping(value = "/employee", method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteLotsEmployee(@RequestParam List<Integer> idList) {
        Msg msg = null;


        int iResult = employeeService.deleteLotsByPrimaryKey(idList);
        System.out.println("deleteLotsEmployee iResult:"+iResult);
        if (iResult > 0) {
            msg = Msg.succeed();
            msg.setMsg("删除成功，共删除" + iResult + "个员工");
        } else {
            msg = Msg.failed();
            msg.setMsg("删除失败!");
        }
        return msg;
    }


    /**
     * 该方法用于更新员工信息
     */
    @RequestMapping(value = "/employee",method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateEmployee(@Valid @RequestBody Employee employee, BindingResult... result){
        Msg msg = null;

        //先检查用户信息有没有错误
//        Map<String,Object> errorMap = employeeService.checkUpdateRole(employee,result);

        //如果都无误，则尝试保存
        if (true){
            int iResult = 0;
            int iRelationResult = 0;
            try {
                iResult = employeeService.updateByPrimaryKeySelective(employee);
//                relationService.updateRelationByRole(role);
            }catch (Exception e){
                e.printStackTrace();
            }
            if (iResult > 0){
                msg = Msg.succeed();
                msg.setMsg("更新成功，共更新"+iResult+"个员工");
            }else {
                msg = Msg.failed();
                msg.setMsg("更新失败!");
            }
        }else {
            msg = Msg.failed();
            msg.setMsg("更新失败！");
            //将详细错误信息添加进msg
//            msg.addData("fieldErrors",errorMap);
        }

        return msg;
    }

}
